<template>
  <div class="page-header-index-wide" style="overflow: hidden;height: 100%;">
    <a-row :gutter="8" style="height: 100%;">
      <a-col :span="16" style="height: 100%;">
        <a-row :gutter="[8,8]" style="height: 50%;">

          <!--     通知公告     -->
          <a-col :span="12" style="height: 100%;">
            <dash-card :loading="noticeCardLoading"
                       :title="'通知公告 （' + noticeCount + '）'"
                       more="isystem-annountCement"
                       :show-tab="false"
                       img-src="dash_notice.png"
            >
              <template>
                <dash-ul
                  style="padding-top: 8px;"
                  :dataList="tzList"
                  :routeJump="handleToNotice"
                />
              </template>
            </dash-card>
          </a-col>

          <!--     法律法规     -->
          <a-col :span="12" style="height: 100%;">
            <dash-card
              :loading="extCardLoading"
              :more="fgTo"
              :show-tab="false"
              img-src="dash_fg.png"
            >
              <template v-slot:title>
                <a-tabs
                  size="small"
                  class="dash_tabs_custom"
                  @change="handleExtChange"
                >
                  <a-tab-pane v-for="item in tabList.sysList" :key="item.key"
                              :tab="formatTabTitle(item.title,item.count)" />
                </a-tabs>
              </template>
              <template>
                <a-spin :spinning="extLoading" style="height: 100%">
                  <dash-ul
                    style="padding-top: 8px;"
                    :dataList="extList"
                    :routeJump="handleToExt"
                  />
                </a-spin>
              </template>
            </dash-card>
          </a-col>
        </a-row>

        <a-row :gutter="[8,8]" style="height: 50%;">
          <!--    分单位计划完成情况    -->
          <a-col :span="12" style="height: 100%;">
            <dash-card :loading="dwLoading"
                       title="分单位计划完成情况"
                       more="sjxmzygl-sjxmgl"
                       :show-tab="false"
                       img-src="dash_tar.png"
            >
              <template>
                <dash-pillar :data-r="annualChartData"></dash-pillar>
              </template>
            </dash-card>
          </a-col>

          <!--     分类型计划完成情况     -->
          <a-col :span="12" style="height: 100%;">
            <dash-card :loading="lxLoading"
                       title="分类型计划完成情况"
                       more="sjxmzygl-xmgdgl"
                       :show-tab="false"
                       img-src="dash_annual.png"
            >
              <template>
                <dash-pie :data-r="annualPieData"></dash-pie>
              </template>
            </dash-card>
          </a-col>
        </a-row>
      </a-col>

      <a-col :span="8" style="height: 100%;">
        <a-row :gutter="[0,8]" style="height: 100%;">
          <a-col :span="24" style="height: 15%;">
            <div class="name-card">
              <div style="display: flex;align-items: center;justify-content: flex-start;width: 80%;height: 100%;">
                <a-avatar :size="64" :src="getAvatar()" />
                <div style="margin-left: 20px;width: 80%;">
                  <div style="width: 100%;display: flex;justify-content: flex-start;align-items: baseline;">
                    <div :title="nickname()"
                      style="font-size: 20px;color: white;font-weight: bold; white-space: nowrap; text-overflow: ellipsis;max-width: 80%;">
                      {{ nickname() }}
                    </div>
                    <div :title="userInfo().loginIp"
                      style="font-size: 14px;color: rgba(255,255,255,0.8);margin-left: 20px;letter-spacing: 0.5px;line-height: 16px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">
                      IP: {{ userInfo().loginIp }}
                    </div>
                  </div>
                  <div
                    style="color:white;font-size: 15px;letter-spacing: 2px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">
                    {{ departInfo().departName }}
                  </div>
                </div>
              </div>
              <div
                style="display: flex;flex-direction: column;align-items: center;color:white;height: 100%;justify-content: center;">
                <span style="font-weight: 600;font-size: 20px;">{{ currentTime }}</span>
                <span style="font-weight: 600;font-size: 15px;letter-spacing: 3px;">{{ currentWeekday }}</span>
              </div>
            </div>
          </a-col>

          <!--     我的本年度办理情况     -->
          <a-col :span="24" style="height: 20%;">
            <dash-card title="我的本年度办理情况"
                       :show-tab="false"
                       :show-more="false"
                       more="sjxmzygl-sjxmgl"
                       img-src="dash_sj.png"
            >
              <template #extra>
                <div>
                  <a-date-picker
                    mode="year"
                    format="YYYY年度"
                    :allowClear="false"
                    value-format="YYYY"
                    placeholder=""
                    v-model="annualYear"
                    :open="yearPickShow"
                    style="background-color: #dbedff;color: #1359b7;"
                    @panelChange="handlePanelChange"
                    @openChange="handleOpenChange"
                  >
                    <template #suffixIcon>
                      <span
                        style="color: #2c62b4;font-size: 10px;text-align: center;display: flex;align-items: center;">▼</span>
                    </template>
                  </a-date-picker>
                </div>
              </template>
              <template #default>
                <a-spin :spinning="blqkLoading" style="height: 100%">
                  <div
                    style="display: flex;justify-content: space-between;align-items: center; height: 100%;width: 100%;padding:1vh;">
                    <div class="annual-card" style="background-color: #bfdfff;cursor: pointer;" @click="handleTodoShow">
                      <div><font class="annual-num">{{ ndblqk.dbNum }}</font>个</div>
                      <div>我的在办</div>
                    </div>
                    <div class="annual-card" style="background-color: #ffe8bd;cursor: pointer;" @click="handleTodoShow('2')">
                      <div><font class="annual-num">{{ ndblqk.ybNum }}</font>个</div>
                      <div>我的办结</div>
                    </div>
                    <div class="annual-card" style="background-color: #bbf1f1;cursor: pointer;" @click="handleTodoShow">
                      <div><font class="annual-num">{{ ndblqk.zNum }}</font>条</div>
                      <div>我的消息</div>
                    </div>
                  </div>
                </a-spin>
              </template>
            </dash-card>
          </a-col>

          <!--    待办    -->
          <a-col :span="24" style="height: 65%;">
            <dash-card
              :loading="dbCardLoading"
              title="待办事件"
              :more="handleTodoShow"
              img-src="dash_todo.png"
            >
              <template>
                <a-tabs
                  size="small"
                  class="dash_tabs"
                  @change="handleTodoChange"
                >
                  <a-tab-pane v-for="item in tabList.todoList" :key="item.key"
                              :tab="formatTabTitle(item.title,item.count)" />
                </a-tabs>
                <a-spin :spinning="dbLoading" style="height: 100%">
                  <dash-ul
                    :dataList="todoList"
                    :routeJump="handleToDetail"
                    :show-urgent="false"
                    :can-disable="true"
                  />
                </a-spin>
              </template>
            </dash-card>
          </a-col>
        </a-row>
      </a-col>
    </a-row>

    <todoListModel ref="todoModel" :todoActive="todoActive" />
  </div>
</template>

<script>
import DashCard from '@views/sj/dashboard/components/DashCard.vue'
import DashUl from '@views/sj/dashboard/components/DashUl.vue'
import { getAction, getFileAccessHttpUrl } from '@api/manage'
import { mapGetters } from 'vuex'
import moment from 'moment/moment'
import todoListModel from '@comp/tools/todoListModel.vue'
import DashPillar from '@views/sj/dashboard/components/DashPillar.vue'
import DashPie from '@views/sj/dashboard/components/DashPie.vue'

export default {
  name: 'IndexCharts',
  components: { DashPie, DashPillar, todoListModel, DashUl, DashCard },
  data() {
    return {
      dwLoading: true,
      lxLoading: true,
      noticeCardLoading: true,
      dbCardLoading: true,
      extCardLoading: true,
      dbLoading: false,
      blqkLoading: false,
      extLoading: false,
      noticeCount: 0,
      tabList: {
        /* noticeList: [
           { title: '全部', count: 0, key: 'all' },
           { title: '通知', count: 0, key: 'info' },
           { title: '公告', count: 0, key: 'notice' }
         ],*/
        todoList: [
          { title: '全部', count: 0, key: '0' },
          { title: '待办', count: 0, key: '1' },
          { title: '已办', count: 0, key: '2' }
        ],
        sysList: [
          {
            title: '法律法规',
            count: 0,
            key: '0',
            url: '/sjzszhly/knowledgeRegulation/queryRegulationListInfo',
            to: 'sjzszhly-sjfggl',
            queryFiled: {
              column: 'createTime',
              order: 'desc',
              pageNo: 1,
              pageSize: 10,
              advType: 1,
              field: 'id,,,title,number,office,setTime,useTime,type_dictText,sxTime,action'
            }
          },
          {
            title: '审计准则',
            count: 0,
            key: '1',
            url: '/sjzszhly/knowledgeGuide/queryGuideListInfo',
            to: 'sjzszhly-sjzzgl',
            queryFiled: {
              column: 'createTime',
              order: 'desc',
              pageNo: 1,
              pageSize: 10,
              advType: 3,
              field: 'id,,,title,type_dictText,number,office,setTime,useTime,action'
            }
          },
          {
            title: '企业制度',
            count: 0,
            key: '2',
            url: '/sjzszhly/knowledgeStation/queryStationListInfo',
            to: 'sjzszhly-sjzdbf',
            queryFiled: {
              column: 'createTime',
              order: 'desc',
              pageNo: 1,
              pageSize: 10,
              advType: 4,
              field: 'id,,,title,office,setTime,useTime,action'
            }
          }
        ]
      },
      url: {
        ybdb: '/sjdb/sjDaiban/queryDbList',
        tjyb: '/audit/index/queryMonthReportList',
        tzgg: '/sys/annountCement/list',
        cyxm: '/audit/index/queryParticipateList',
        sjry: '/audit/index/queryList',
        xmss: '/audit/index/queryShishiDetail',
        jxkh: '/audit/index/queryCheck',
        navigation: '/audit/index/queryQuickMenu?filter=online&number=9',
        blqk: '/sjdb/sjDaiban/queryCurYearBlqk',
        queryBnssqkNumer: '/audit/index/queryBnssqkNumer',
        queryGzzdNumer: '/audit/index/queryGzzdNumer',
        tree: '/common/knowledgeCommon/queryAllTypesList',
        classification:'/audit/index/queryClassificationList'
      },
      treeData: [],
      tzList: [], // 通知公告
      todoList: [], // 待办
      extList: [], // 法律、审计、制度
      ndblqk: {
        zNum: '0',
        dbNum: '0',
        ybNum: '0'
      }, // 年度办理情况
      annualYear: new Date().getFullYear().toString(),
      yearPickShow: false,
      currentTime: this.getCurrentTime(),
      currentWeekday: this.getCurrentWeekday(),
      columns: [
        {
          title: '机构名称',
          align: 'center',
          dataIndex: 'deptName',
          width: 100,
          customHeaderCell: () => ({
            style: { backgroundColor: '#004ca7', color: 'white', fontSize: '12px' }
          }),
          customCell: () => ({
            style: { backgroundColor: '#ccdbed', fontSize: '12px' }
          })
        },
        {
          title: () => {
            const totalPlan = this.annualData.reduce((sum, item) => sum + (parseFloat(item.jh) || 0), 0) // 转换为数字
            return `本年计划\r\n（${totalPlan}）`
          },
          align: 'center',
          dataIndex: 'jh',
          customHeaderCell: () => ({
            style: { backgroundColor: '#3370b9', color: 'white', fontSize: '12px', whiteSpace: 'pre-wrap' }
          }),
          customCell: () => ({
            style: { backgroundColor: '#e6edf6', fontSize: '14px', fontWeight: 'bold' }
          })
        },
        {
          title: () => {
            const totalPlan = this.annualData.reduce((sum, item) => sum + (parseFloat(item.ss) || 0), 0) // 转换为数字
            return `实施阶段\r\n（${totalPlan}）`
          },
          align: 'center',
          dataIndex: 'ss',
          customHeaderCell: () => ({
            style: { backgroundColor: '#3993dd', color: 'white', fontSize: '12px', whiteSpace: 'pre-wrap' }
          }),
          customCell: () => ({
            style: { backgroundColor: '#e7f2fb', fontSize: '14px', fontWeight: 'bold' }
          })
        },
        {
          title: () => {
            const totalPlan = this.annualData.reduce((sum, item) => sum + (parseFloat(item.bg) || 0), 0) // 转换为数字
            return `报告阶段\r\n（${totalPlan}）`
          },
          align: 'center',
          dataIndex: 'bg',
          customHeaderCell: () => ({
            style: { backgroundColor: '#6694ca', color: 'white', fontSize: '12px', whiteSpace: 'pre-wrap' }
          }),
          customCell: () => ({
            style: { backgroundColor: '#e6edf6', fontSize: '14px', fontWeight: 'bold' }
          })
        },
        {
          title: () => {
            const totalPlan = this.annualData.reduce((sum, item) => sum + (parseFloat(item.bnwc) || 0), 0) // 转换为数字
            return `本年完成\r\n（${totalPlan}）`
          },
          align: 'center',
          dataIndex: 'bnwc',
          customHeaderCell: () => ({
            style: { backgroundColor: '#6bade6', color: 'white', fontSize: '12px', whiteSpace: 'pre-wrap' }
          }),
          customCell: () => ({
            style: { backgroundColor: '#e7f2fb', fontSize: '14px', fontWeight: 'bold' }
          })
        }
      ],
      annualData: [],
      classificationData: [],
      fgTo: '',
      scrollTimer: null,
      scrollY: 0,
      todoActive:'1',
    }
  },
  created() {
  },

  computed: {
    annualChartData() {
      return this.annualData.map(item => {
        return {
          name: item.deptName,
          unitUnderAudit: item.id,
          value: {
            jh: item.jh || 0,
            wc: item.bnwc || 0
          }
        }
      })
    },
    annualPieData() {
      return this.classificationData.map(item => {
        return {
          name: item.proTypeName,
          value: item.wcs,
          proTypeId: item.proTypeId
        }
      })
    }
  },

  mounted() {
    this.timer = setInterval(() => {
      this.currentTime = new Date().toLocaleTimeString()
    }, 1000)

    this.$nextTick(() => {
      this.updateScrollY() // 确保 DOM 渲染完成后计算 scrollY
      window.addEventListener('resize', this.updateScrollY) // 监听窗口变化
    })

    this.loadTree()

    this.handleNoticeChange()
    this.handleTodoChange(0)
    this.handleExtChange(0)

    this.blqk()
    this.queryBnssqkNumer()
    this.queryClassification()
    this.queryGzzdNumer()
  },

  methods: {
    loadTree() {
      this.treeData = []
      getAction(this.url.tree, { type: 4 }).then((res) => {
        if (res.success) {
          this.treeData = res.result
        }
      })
    },

    getTitleByKey(data, targetKey) {
      for (let item of data) {
        if (item.key === targetKey) {
          return item.title
        }
        if (item.children && item.children.length > 0) {
          const result = this.getTitleByKey(item.children, targetKey)
          if (result) {
            return result
          }
        }
      }
      return null // 没有找到对应key
    },

    /**
     * 年度办理情况
     */
    blqk() {
      this.blqkLoading = true
      getAction(this.url.blqk, { year: this.annualYear })
        .then((res) => {
          if (res.success && res.result) {
            this.ndblqk = {
              zNum: res.result.znum || '0',
              dbNum: res.result.dbNum || '0',
              ybNum: res.result.ybNum || '0'
            }
          } else {
            this.ndblqk = {
              zNum: '0',
              dbNum: '0',
              ybNum: '0'
            }
          }
        }).finally(() => {
        this.blqkLoading = false
      })
    },

    /**
     * 年度审计项目实施情况
     */
    queryBnssqkNumer() {
      getAction(this.url.queryBnssqkNumer, {})
        .then((res) => {
          if (res.success && res.result) {
            this.annualData = res.result
          }
        }).finally(() => {
        this.dwLoading = false
      })
    },

    /**
     * 按类别统计
     */
    queryClassification() {
      getAction(this.url.classification, {})
        .then((res) => {
          if (res.success && res.result) {
            this.classificationData = res.result
          }
        }).finally(() => {
        this.lxLoading = false
      })
    },

    /**
     * 规章制度数量统计
     */
    queryGzzdNumer() {
      const map = {
        '0': 'flfgNum',
        '1': 'zzNum',
        '2': 'zdNum'
      }
      getAction(this.url.queryGzzdNumer, {})
        .then((res) => {
          if (res.success && res.result) {
            this.tabList.sysList.forEach(item => item.count = parseInt(res.result[map[item.key]]))
          }
        }).finally(() => {
      })
    },

    async handleNoticeChange() {
      const data = await getAction(this.url.tzgg, { sendStatus: 1, pageNo: 1, pageSize: 10 })
      if (data && data.result) {
        this.tzList = data.result.records.map(item => {
          return {
            ...item,
            title: item.titile,
            time: item.createTime
          }
        })

        this.noticeCount = data.result.total
      }
      this.noticeCardLoading = false
    },

    async handleTodoChange(key) {
      this.dbLoading = true
      this.todoList = []
      let url = !!key ? `${this.url.ybdb}?state=${key}&&pageNo=1&&pageSize=1000` : `${this.url.ybdb}?pageNo=1&&pageSize=1000`
      const data = await getAction(url)
      if (data && data.result) {
        if (key == '0') {
          this.tabList.todoList[0].count = data.result.total
          this.tabList.todoList[1].count = data.result.records.filter(i => i.state == '1').length
          this.tabList.todoList[2].count = data.result.records.filter(i => i.state == '2').length
        }
        this.todoList = data.result.records.map(item => {
          return {
            ...item,
            title: item.title,
            time: item.subTime,
            typeContent: item.task,
            showCircle: item.state == '1'
          }
        }).splice(0, 10)
      }
      this.dbLoading = false
      this.dbCardLoading = false
    },

    async handleExtChange(key) {
      let that = this

      this.extLoading = true
      this.extList = []
      const typeT = this.tabList.sysList.filter(e => e.key == key)[0]
      this.fgTo = typeT.to
      const data = await getAction(typeT.url, typeT.queryFiled)
      if (data && data.result) {
        this.extList = data.result.records.map(item => {
          return {
            ...item,
            time: item.setTime,
            typeContent: key == '2' ? that.getTitleByKey(that.treeData, item.cate) : item.type_dictText
          }
        })
      }
      this.extCardLoading = false
      this.extLoading = false
    },

    handleToNotice(record) {
      if (record.isOpen == 1 && record.openPage) {
        this.$router.push({
          name: record.openPage,
          query: { number: record.busId }
        })
      } else {
        this.$router.push({
          name: 'isystem-annountCement',
          query: { titile: record.titile }
        })
      }
    },

    handleToExt(record) {
      this.$router.push({ name: this.fgTo, params: { title: record.title } })
    },

    handleToDetail(record) {
      if (record.href) {
        this.$router.push(record.href)
        this.$emit('closed')
      } else {
        this.$message.error('未找到该路径！')
      }
    },

    handleTodoShow(active) {
      if (typeof active == 'string') {
        this.todoActive = active
      } else {
        this.todoActive = '1'
      }
      this.$refs['todoModel'].visible = true
    },

    formatTabTitle(title, count) {
      return `${title}（${count}）`
    },

    ...mapGetters(['nickname', 'avatar', 'userInfo', 'departInfo']),
    getAvatar() {
      return getFileAccessHttpUrl(this.avatar())
    },

    getCurrentTime() {
      return new Date().toLocaleTimeString() // 获取当前时间
    },

    getCurrentWeekday() {
      const daysOfWeek = ['日', '一', '二', '三', '四', '五', '六']
      const date = new Date()
      return `星期${daysOfWeek[date.getDay()]}` // 获取当前星期
    },

    handlePanelChange(value) {
      this.annualYear = moment(value).format('YYYY')
      this.blqk()
      this.yearPickShow = false
    },

    // 弹出日历和关闭日历的回调
    handleOpenChange(status) {
      this.yearPickShow = status
    },

    scrollFun() {
      if (this.scrollTimer) {
        clearInterval(this.scrollTimer)
        this.scrollTimer = null
      }
      this.scrollTimer = setInterval(() => {
        const scrollBody = document.querySelectorAll(`.tableRect .ant-table-body`)
        if (scrollBody.length > 0) {
          const scroll = scrollBody[0].scrollHeight - scrollBody[0].clientHeight
          const scrollTop = scrollBody[0].scrollTop
          // 滚动速度
          const temp = scrollTop + 1
          scrollBody[0].scrollTop = temp // 滚动
          // 滚动到底部 置顶
          if (scroll <= temp) {
            scrollBody[0].scrollTop = 0
          }
        }
      }, 80)
    },

    pauseScroll() {
      if (this.scrollTimer) {
        clearInterval(this.scrollTimer)
        this.scrollTimer = null
      }
    },

    updateScrollY() {
      const scrollBody = this.$refs.scrollBody
      if (scrollBody) {
        const antCardBody = scrollBody.$el.querySelector('.ant-card-body')
        if (antCardBody) {
          const height = antCardBody.clientHeight  // 获取高度
          this.scrollY = height - 60
        }
      }
    }
  },

  beforeDestroy() {
    // 清除定时器
    clearInterval(this.timer)
    clearInterval(this.scrollTimer)

    window.removeEventListener('resize', this.updateScrollY) // 清理监听器
  }
}
</script>
<style lang="less" scoped>
@import './index.less';

.name-card {
  height: 100%;
  background-image: url('~@/assets/dash_bg.jpg');
  background-size: 100%;
  border-radius: 5px;
  padding: 20px 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.dash_tabs {
  /deep/ .ant-tabs-tab {
    font-size: 13px;
    padding: 8px 0;
  }
}

.dash_tabs_custom {
  width: 100%;

  /deep/ .ant-tabs-tab {
    font-weight: 600;
    font-size: 14px;
    color: #000000D9;
    padding: 0 16px 8px 8px
  }
}

.annual-card {
  width: 31%;
  height: 100%;
  background-color: #bfdfff;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .annual-num {
    font-size: 22px;
    font-weight: bold;
  }
}

/deep/ .ant-input {
  background-color: #dbedff;
  border: rgba(255, 255, 255, 0);
  color: #2c62b4;
  font-weight: bold;
  font-size: 12px;
  width: 95px;
  cursor: pointer;
}

.mod_table {
  height: 100%;
  --back-color: rgb(255, 255, 255);
}

.mod_table {
  /deep/ .ant-table-bordered .ant-table-body > table {
    border: unset;
  }

  /deep/ .ant-table-thead > tr > th {
    padding: 8px 5px;
    border-top: 2px solid var(--back-color);
    border-left: 2px solid var(--back-color);
    border-bottom: 2px solid var(--back-color);
    border-right: unset;
  }

  /deep/ .ant-table-thead > tr > th:last-of-type {
    border-right: 2px solid var(--back-color);
  }

  /deep/ .ant-table-tbody > tr > td {
    padding: 8px 5px;
    border-bottom: 2px solid var(--back-color);
    border-left: 2px solid var(--back-color);
    border-right: unset;
  }

  /deep/ .ant-table-tbody > tr > td:last-of-type {
    border-right: 2px solid var(--back-color);
  }
}

/deep/ .ant-spin-container {
  height: 100%;
}

/deep/ .mod_table .ant-table-hide-scrollbar {
  scrollbar-color: unset;
  margin-bottom: -10px !important;
}

</style>